import os
from flask import request, app
from flask_restful import Resource
from werkzeug.utils import secure_filename

ALLOWED_EXTENSIONS = {'txt', 'pdf', 'jpg', 'mp4', 'webm'}  # 文件允许上传格式

UPLOAD_FOLDER = 'tmp/uploads'  # 文件下载路径


# ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

def allowed_file(filename):  # 通过将文件名分段的方式查询文件格式是否在允许上传格式范围之内
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


class Upload(Resource):

    def post(self):
        file = request.files["file"]
        if file and allowed_file(file.filename):  # 当确认有上传文件并且格式合法
            filename = secure_filename(file.filename)  # 使用secure_filename()让文件名变得安全
            file.save(os.path.join(UPLOAD_FOLDER, filename))
            # 保存文件，也可以直接写成f.save(os.path.join(UPLOAD_FOLDER, fname))
            return 'success', 200
        return "upload fail", 200

